#include <iostream>
#include <vector>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define NUM 4

int tickets = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* buyTicket(void* args)
{
    char* name = (char*)args;
    while (true)
    {
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&cond, &lock);
        if (tickets <= 0)
        {
            pthread_mutex_unlock(&lock);
            break;
        }
        cout << name << "正在抢票 " << tickets << endl;
        tickets--; 
        pthread_mutex_unlock(&lock);
    }
    delete[] name;
    return nullptr;
}

int main()
{
    vector<pthread_t> threads(NUM);
    for (int i = 0 ; i < NUM; i++)
    {
        char* name = new char[64];
        snprintf(name, 64, "user%d", i + 1);
        pthread_create(&threads[i], nullptr, buyTicket, name);
    }
    while (true)
    {
        usleep(1234);
        pthread_cond_broadcast(&cond);//唤醒在条件变量上等待的线程
    }
    for (int i = 0; i < NUM; i++)
    {
        pthread_join(threads[i], nullptr);
    }
    return 0;
}
